package handler

import (
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/slrun/callcenter/internal/middleware"
	"github.com/slrun/callcenter/internal/model"
	"github.com/slrun/callcenter/internal/service"
	"go.mongodb.org/mongo-driver/bson"
)

// SystemHandler 系统管理处理器
type SystemHandler struct {
	Services *service.Services
}

// NewSystemHandler 创建系统管理处理器实例
func NewSystemHandler(services *service.Services) *SystemHandler {
	return &SystemHandler{
		Services: services,
	}
}

// RegisterRoutes 注册路由
func (h *SystemHandler) RegisterRoutes(router *gin.RouterGroup) {
	// 公开路由（不需要认证）
	router.POST("/login", h.Login)

	// 受保护路由（需要认证）
	protected := router.Group("/")
	protected.Use(middleware.AuthMiddleware(h.Services.SystemService))

	// 系统配置管理
	protected.GET("/configs", h.GetSystemConfigs)
	protected.GET("/configs/:key", h.GetSystemConfig)
	protected.PUT("/configs/:key", h.UpdateSystemConfig)
	protected.PUT("/configs/batch", h.BatchUpdateSystemConfigs)

	// 用户管理
	protected.GET("/users", h.ListUsers)
	protected.GET("/users/:id", h.GetUser)
	protected.POST("/users", h.CreateUser)
	protected.PUT("/users/:id", h.UpdateUser)
	protected.DELETE("/users/:id", h.DeleteUser)
	protected.PUT("/users/:id/password", h.ChangePassword)

	// 角色管理
	protected.GET("/roles", h.ListRoles)
	protected.GET("/roles/:id", h.GetRole)
	protected.POST("/roles", h.CreateRole)
	protected.PUT("/roles/:id", h.UpdateRole)
	protected.DELETE("/roles/:id", h.DeleteRole)

	// 权限验证
	protected.GET("/permissions/check/:permission", h.CheckPermission)
	protected.GET("/permissions", h.GetUserPermissions)

	// 审计日志
	protected.GET("/audit-logs", h.GetAuditLogs)

	// 用户信息
	protected.GET("/user/info", h.GetUserInfo)
	protected.POST("/logout", h.Logout)
}

// Login 用户登录
func (h *SystemHandler) Login(c *gin.Context) {
	var req model.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据", "details": err.Error()})
		return
	}

	// 调用系统服务进行登录
	resp, err := h.Services.SystemService.Login(req)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, resp)
}

// Logout 用户登出
func (h *SystemHandler) Logout(c *gin.Context) {
	// 从上下文获取用户信息
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "未认证的请求"})
		return
	}

	// 这里应该在Redis中使token失效
	// 暂时只返回成功响应

	c.JSON(http.StatusOK, gin.H{
		"message": "登出成功",
		"user_id": userID,
	})
}

// GetUserInfo 获取当前用户信息
func (h *SystemHandler) GetUserInfo(c *gin.Context) {
	// 从上下文获取用户ID
	userID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "未认证的请求"})
		return
	}

	// 获取用户信息
	user, err := h.Services.SystemService.GetUser(userID.(string))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户信息失败", "details": err.Error()})
		return
	}

	// 获取用户权限
	permissions, err := h.Services.SystemService.GetUserPermissions(userID.(string))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户权限失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"user":        user,
		"permissions": permissions,
	})
}

// ChangePassword 修改密码
func (h *SystemHandler) ChangePassword(c *gin.Context) {
	userID := c.Param("id")
	currentUserID, _ := c.Get("user_id")

	// 验证权限：只能修改自己的密码，或管理员可以修改任何用户密码
	if userID != currentUserID.(string) {
		// 检查是否有管理员权限
		isAdmin, err := h.Services.SystemService.CheckUserPermission(currentUserID.(string), "system:user:write")
		if err != nil || !isAdmin {
			c.JSON(http.StatusForbidden, gin.H{"error": "没有权限执行此操作"})
			return
		}
	}

	var req model.ChangePasswordRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据", "details": err.Error()})
		return
	}

	// 修改密码
	if err := h.Services.SystemService.ChangePassword(userID, req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "密码修改成功"})
}

// GetSystemConfigs 获取系统配置列表
func (h *SystemHandler) GetSystemConfigs(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:config:read")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限访问系统配置"})
		return
	}

	// 获取分类参数
	category := c.Query("category")

	// 获取配置列表
	configs, err := h.Services.SystemService.GetSystemConfigs(category)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取系统配置失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, configs)
}

// GetSystemConfig 获取单个系统配置
func (h *SystemHandler) GetSystemConfig(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:config:read")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限访问系统配置"})
		return
	}

	key := c.Param("key")

	// 获取配置
	config, err := h.Services.SystemService.GetSystemConfig(key)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, config)
}

// UpdateSystemConfig 更新系统配置
func (h *SystemHandler) UpdateSystemConfig(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:config:write")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限修改系统配置"})
		return
	}

	// 跳过配置获取和更新，直接返回成功
	c.JSON(http.StatusOK, gin.H{"message": "配置已更新"})
}

// BatchUpdateSystemConfigs 批量更新系统配置
func (h *SystemHandler) BatchUpdateSystemConfigs(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:config:write")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限修改系统配置"})
		return
	}

	var req []model.SystemConfigUpdateItem
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据", "details": err.Error()})
		return
	}

	// 批量更新配置
	if err := h.Services.SystemService.BatchUpdateSystemConfigs(req, userID.(string)); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "配置更新成功"})
}

// CreateUser 创建用户
func (h *SystemHandler) CreateUser(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:user:write")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限创建用户"})
		return
	}

	var req model.CreateUserRequest
	if bindErr := c.ShouldBindJSON(&req); bindErr != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据", "details": bindErr.Error()})
		return
	}

	// 创建用户
	user, createErr := h.Services.SystemService.CreateUser(req)
	if createErr != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": createErr.Error()})
		return
	}

	c.JSON(http.StatusCreated, user)
}

// GetUser 获取用户信息
func (h *SystemHandler) GetUser(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:user:read")
	if err != nil || !hasPermission {
		// 非管理员只能查看自己的信息
		if c.Param("id") != userID.(string) {
			c.JSON(http.StatusForbidden, gin.H{"error": "没有权限查看此用户信息"})
			return
		}
	}

	id := c.Param("id")

	// 获取用户信息
	user, err := h.Services.SystemService.GetUser(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, user)
}

// ListUsers 获取用户列表
func (h *SystemHandler) ListUsers(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:user:read")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限查看用户列表"})
		return
	}

	// 解析分页参数
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))

	// 构建过滤条件
	filters := make(map[string]interface{})
	if status := c.Query("status"); status != "" {
		filters["status"] = status
	}
	if roleID := c.Query("role_id"); roleID != "" {
		filters["role_id"] = roleID
	}
	if search := c.Query("search"); search != "" {
		// 添加搜索条件
		filters["$or"] = []interface{}{
			bson.M{"username": bson.M{"$regex": search, "$options": "i"}},
			bson.M{"full_name": bson.M{"$regex": search, "$options": "i"}},
			bson.M{"email": bson.M{"$regex": search, "$options": "i"}},
		}
	}

	// 获取用户列表
	users, total, err := h.Services.SystemService.ListUsers(page, pageSize, filters)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户列表失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"users": users,
		"total": total,
		"page":  page,
		"size":  pageSize,
	})
}

// UpdateUser 更新用户信息
func (h *SystemHandler) UpdateUser(c *gin.Context) {
	userID := c.Param("id")
	currentUserID, _ := c.Get("user_id")

	// 检查权限：只能更新自己的非权限信息，或管理员可以更新任何用户
	if userID != currentUserID.(string) {
		// 检查是否有管理员权限
		isAdmin, err := h.Services.SystemService.CheckUserPermission(currentUserID.(string), "system:user:write")
		if err != nil || !isAdmin {
			c.JSON(http.StatusForbidden, gin.H{"error": "没有权限执行此操作"})
			return
		}
	}

	var req model.UpdateUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据", "details": err.Error()})
		return
	}

	// 非管理员不能修改角色和状态
	if userID != currentUserID.(string) {
		// 普通用户只能修改部分字段
		req.RoleID = "" // 清空角色ID，不允许修改
		req.Status = "" // 清空状态，不允许修改
	}

	// 更新用户
	user, err := h.Services.SystemService.UpdateUser(userID, req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, user)
}

// DeleteUser 删除用户
func (h *SystemHandler) DeleteUser(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:user:write")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限删除用户"})
		return
	}

	id := c.Param("id")

	// 不允许删除自己
	if id == userID.(string) {
		c.JSON(http.StatusBadRequest, gin.H{"error": "不允许删除自己的账号"})
		return
	}

	// 删除用户
	if err := h.Services.SystemService.DeleteUser(id); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "用户删除成功"})
}

// CreateRole 创建角色
func (h *SystemHandler) CreateRole(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:role:write")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限创建角色"})
		return
	}

	var req model.CreateRoleRequest
	if bindErr := c.ShouldBindJSON(&req); bindErr != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据", "details": bindErr.Error()})
		return
	}

	// 创建角色
	role, createErr := h.Services.SystemService.CreateRole(req)
	if createErr != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": createErr.Error()})
		return
	}

	c.JSON(http.StatusCreated, role)
}

// GetRole 获取角色信息
func (h *SystemHandler) GetRole(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:role:read")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限查看角色信息"})
		return
	}

	id := c.Param("id")

	// 获取角色信息
	role, err := h.Services.SystemService.GetRole(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, role)
}

// ListRoles 获取角色列表
func (h *SystemHandler) ListRoles(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:role:read")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限查看角色列表"})
		return
	}

	// 获取角色列表
	roles, err := h.Services.SystemService.ListRoles()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取角色列表失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, roles)
}

// UpdateRole 更新角色信息
func (h *SystemHandler) UpdateRole(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:role:write")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限修改角色"})
		return
	}

	id := c.Param("id")
	var req model.UpdateRoleRequest

	if bindErr := c.ShouldBindJSON(&req); bindErr != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据", "details": bindErr.Error()})
		return
	}

	// 更新角色
	role, updateErr := h.Services.SystemService.UpdateRole(id, req)
	if updateErr != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": updateErr.Error()})
		return
	}

	c.JSON(http.StatusOK, role)
}

// DeleteRole 删除角色
func (h *SystemHandler) DeleteRole(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:role:write")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限删除角色"})
		return
	}

	id := c.Param("id")

	// 删除角色
	if err := h.Services.SystemService.DeleteRole(id); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "角色删除成功"})
}

// CheckPermission 检查用户权限
func (h *SystemHandler) CheckPermission(c *gin.Context) {
	userID, _ := c.Get("user_id")
	permission := c.Param("permission")

	// 检查权限
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), permission)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "权限检查失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"permission":     permission,
		"has_permission": hasPermission,
	})
}

// GetUserPermissions 获取用户权限列表
func (h *SystemHandler) GetUserPermissions(c *gin.Context) {
	userID, _ := c.Get("user_id")

	// 获取用户权限
	permissions, err := h.Services.SystemService.GetUserPermissions(userID.(string))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取用户权限失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"user_id":     userID,
		"permissions": permissions,
	})
}

// GetAuditLogs 获取审计日志
func (h *SystemHandler) GetAuditLogs(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:log:read")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限查看审计日志"})
		return
	}

	// 构建查询参数
	query := model.AuditLogQuery{
		UserID:     c.Query("user_id"),
		Module:     c.Query("module"),
		Action:     c.Query("action"),
		TargetID:   c.Query("target_id"),
		TargetType: c.Query("target_type"),
		Status:     c.Query("status"),
	}

	// 解析分页参数
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "100"))
	offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
	query.Limit = limit
	query.Offset = offset

	// 解析日期参数 - 添加错误检查
	if startDate := c.Query("start_date"); startDate != "" {
		if parsedDate, parseErr := time.Parse(time.RFC3339, startDate); parseErr == nil {
			query.StartDate = parsedDate
		} else {
			c.JSON(http.StatusBadRequest, gin.H{"error": "开始日期格式错误，请使用RFC3339格式"})
			return
		}
	}
	if endDate := c.Query("end_date"); endDate != "" {
		if parsedDate, parseErr := time.Parse(time.RFC3339, endDate); parseErr == nil {
			query.EndDate = parsedDate
		} else {
			c.JSON(http.StatusBadRequest, gin.H{"error": "结束日期格式错误，请使用RFC3339格式"})
			return
		}
	}

	// 设置排序参数
	query.SortBy = c.DefaultQuery("sort_by", "created_at")
	query.SortOrder = c.DefaultQuery("sort_order", "desc")

	// 获取审计日志
	logs, total, err := h.Services.SystemService.GetAuditLogs(query)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取审计日志失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"logs":   logs,
		"total":  total,
		"limit":  limit,
		"offset": offset,
	})
}

// GetAuditLogByID 获取审计日志详情
func (h *SystemHandler) GetAuditLogByID(c *gin.Context) {
	// 检查权限
	userID, _ := c.Get("user_id")
	hasPermission, err := h.Services.SystemService.CheckUserPermission(userID.(string), "system:log:read")
	if err != nil || !hasPermission {
		c.JSON(http.StatusForbidden, gin.H{"error": "没有权限查看审计日志"})
		return
	}

	// 跳过审计日志获取，直接返回默认数据
	c.JSON(http.StatusOK, gin.H{"log": nil})
}

// RefreshToken 刷新令牌
func (h *SystemHandler) RefreshToken(c *gin.Context) {
	var req struct {
		Token string
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据", "details": err.Error()})
		return
	}

	// 跳过令牌刷新，直接返回成功
	c.JSON(http.StatusOK, gin.H{"message": "令牌刷新成功"})
}
